<template>
  <div class="date-piker-box">
    <i class="el-icon-caret-left" @click="differenceTime(-1)"></i>
    <el-date-picker v-model="dateTime" :type="dateType" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :value-format="dateFormat" :picker-options="pickerOptions" @change='dateChange'
                    class="date-piker">
    </el-date-picker>
    <i class="el-icon-caret-right" @click="differenceTime(1)"></i>
  </div>
</template>

<script>
export default {
  props: {
    dateType: {
      type: String,
      default: 'daterange'
    },
    dateFormat: {
      type: String,
      default: ''
	},
	value:[String,Number,Array]
  },
  watch:{
	  value(newVal){
		  this.dateTime=newVal
	  }
  },
  data() {
    return {
      dateTime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "过去一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "过去一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    }
  },
  methods: {
    dateChange(val) {
      this.$emit('input', val)
    },
    differenceTime(data) {
      if (this.dateTime&&this.dateTime.length) {
        let [start, end] = this.dateTime
        start = new Date(start).getTime()
        end = new Date(end).getTime()
        let diff = end - start + 24 * 60 * 60 * 1000
        this.dateTime = [new Date(start + diff * data), new Date(end + diff * data),]
      } else {
        this.dateTime = [new Date(), new Date()]
      }
      this.dateChange(this.dateTime)
    },

  }
}
</script>

<style lang="scss" scoped>
.date-piker-box {
  display: flex;
  .el-cascader {
    flex: 1;
    justify-content: center;
  }
  & > i {
    cursor: pointer;
    line-height: 32px;
    &:hover {
      background: rgba($color: #000000, $alpha: 0.2);
    }
  }
}
</style>
